let DIR = cc.Enum({
    UP: 0,
    RIGHT: 1,
    DOWN: 2,
    LEFT: 3
});
cc.Class({
    extends: cc.Component,

    properties: {
        map: {
            default: null,
            type: cc.TiledMap,
        },
        mainLayer: {
            default: null,
            type: cc.TiledLayer,
        },
        player: {
            default: null,
            type: cc.Node,
        },
    },

    // onLoad () {},

    start() {
        this.loadMap();

        this.schedule(function () {
            if (this.playerDir == DIR.DOWN) {
                this.playerTile.y++;
                if (this.playerTile.y >= 22) {
                    this.playerDir = DIR.UP;
                }
            } else if (this.playerDir == DIR.UP) {
                this.playerTile.y--;
                if (this.playerTile.y <= 0) {
                    this.playerDir = DIR.DOWN;
                }
            }
            let playerTarTile = cc.v2(this.playerTile.x, this.playerTile.y);
            this.tryMoveToTarTile(playerTarTile);
        }, 1);
    },
    tryMoveToTarTile(newTilePos) {
        // 让玩家别撞到了墙上
        if (this.mainLayer.getTileGIDAt(newTilePos)) {
            cc.log('hit the wall .');
            return;
        }
        this.playerTile = newTilePos;
        this.updatePlayerPos();

    },
    loadMap() {
        // 获取对象层
        let objects = this.map.getObjectGroup('objects');
        // 获取对象
        let playerObj = objects.getObject('player');
        // 获取坐标
        let playerPos = cc.v2(playerObj.offset.x, playerObj.offset.y);
        // 玩家的瓦片坐标
        this.playerTile = this.getTilePosition(playerPos);
        // 更新玩家的位置
        this.updatePlayerPos();

        this.playerDir = DIR.DOWN;
    },
    updatePlayerPos() {
        let pos = this.mainLayer.getPositionAt(this.playerTile);
        cc.log("player pos:" + pos);
        this.player.setPosition(pos);

        // if (this.playerDir == DIR.DOWN) {
        //     this.map.node.setPosition(this.map.node.x, this.map.node.y + 116);
        // } else if (this.playerDir == DIR.UP) {
        //     this.map.node.setPosition(this.map.node.x, this.map.node.y - 116);
        // }
    },
    //将地图中的坐标转为瓦片的坐标
    getTilePosition(posInPixel) {
        let tileSize = this.map.getTileSize();
        let x = Math.floor(posInPixel.x / tileSize.width);
        let y = Math.floor(posInPixel.y / tileSize.height);
        return cc.v2(x, y);
    },
    update(dt) {
        // if (this.mainLayer.getPositionAt(this.playerTile).y < 375) {
        //     this.map.y -= 236;
        // }
    },
});